package com.fjwt.gz.core.utils;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;
import java.util.Base64;

@Slf4j
public class DESUtil {

    public static final String DES_KEY = "defaultKey";
 
    /**
     * 偏移变量，固定占8位字节
     */
    private final static String IV_PARAMETER = "12345678";
    /**
     * 密钥算法
     */
    private static final String ALGORITHM = "DES";
    /**
     * 加密/解密算法-工作模式-填充模式
     */
    private static final String CIPHER_ALGORITHM = "DES/CBC/PKCS5Padding";
    /**
     * 默认编码
     */
    private static final String CHARSET = "utf-8";

    /**
     * 生成key
     *
     * @param password
     * @return
     * @throws Exception
     */
    private static Key generateKey(String password) throws Exception {
        DESKeySpec dks = new DESKeySpec(password.getBytes(CHARSET));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        return keyFactory.generateSecret(dks);
    }
 
 
    /**
     * DES加密字符串
     *
     * @param password 加密密码，长度不能够小于8位
     * @param data 待加密字符串
     * @return 加密后内容
     */
    public static String encrypt(String password, String data) {
        if (password== null || password.length() < 8) {
            throw new RuntimeException("加密失败，key不能小于8位");
        }
        if (data == null)
            return null;
        try {
            Key secretKey = generateKey(password);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
            byte[] bytes = cipher.doFinal(data.getBytes(CHARSET));
 
            //JDK1.8及以上可直接使用Base64，JDK1.7及以下可以使用BASE64Encoder
            //Android平台可以使用android.util.Base64
            return new String(Base64.getEncoder().encode(bytes));
 
        } catch (Exception e) {
            log.error("DES加密失败",e);
            return data;
        }
    }
 
    /**
     * DES解密字符串
     *
     * @param password 解密密码，长度不能够小于8位
     * @param data 待解密字符串
     * @return 解密后内容
     */
    public static String decrypt(String password, String data) throws Exception {
        if (password== null || password.length() < 8) {
            throw new RuntimeException("加密失败，key不能小于8位");
        }
        if (data == null)
            return null;
        try {
            Key secretKey = generateKey(password);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
            cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
            return new String(cipher.doFinal(Base64.getDecoder().decode(data.getBytes(CHARSET))), CHARSET);
        } catch (Exception e) {
            log.error("DES解密失败",e);
            throw e;
        }
    }

    /**
     * DES解密字符串（解密十六进制加密内容）
     *
     * @param password 解密密码，长度不能够小于8位
     * @param hexData  待解密字符串
     * @return 解密后内容
     */
    public static String decryptFromHex(String password, String hexData) {
        log.info("decryptFromHex-解密前：{}", hexData);
        if (password == null || password.length() < 8) {
            log.error("解密失败，key不能小于8位");
            return null;
        }
        if (StrUtil.isBlank(hexData)) {
            return null;
        }
        hexData = hexData.replaceAll(",", "").trim();
        try {
            Key secretKey = generateKey(password);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
            cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
            // 将十六进制字符串转换为字节数组
            byte[] dataBytes = new byte[hexData.length() / 2];
            for (int i = 0; i < hexData.length(); i += 2) {
                dataBytes[i / 2] = (byte) ((Character.digit(hexData.charAt(i), 16) << 4)
                        + Character.digit(hexData.charAt(i + 1), 16));
            }
            // 进行解密操作
            byte[] decryptedData = cipher.doFinal(dataBytes);
            String res = new String(decryptedData, CHARSET);
            log.info("decryptFromHex-解密后：{}", res);
            return res;
        } catch (Exception e) {
            log.error("DES解密失败", e);
            return null;
        }
    }

    /**
     * DES解密id字符串
     *
     * @param str 待解密字符串
     * @return java.lang.String
     * @author linc
     */
    public static String decryptId(String str) {
        // 大于5个字符才解密
        String res = str;
        if (str.length() > 5) {
            res = decryptFromHex(DES_KEY, str);
        }
        return res;
    }

    public static void main(String[] args) throws Exception {
        System.out.println(encrypt(DES_KEY, "{\"beginTime\":\"2025-03-03 00:00:00\",\"endTime\":\"2025-03-03 16:04:07\"}"));
//        System.out.println(encrypt(DES_KEY, "{\"pageNo\":1,\"pageSize\":99,\"userOpenid\":\"oy7am061bXLX_9iZUZ6BjGbN8wyY\"}"));
//        String str="{\"actId\":\"1\"}";
        String data = "KSVAVVY6Nnmv6xRXeZ9l8KtBOXyc/n5uXUAQUsyp3Gj3bwuN/omO8BIEEnJB3r1und3T1SbRYwWEOLzfd/eSL7R3eglwnm2mcss2kHJPMcoyLWrLvNfvImi0O9o37czpAq7R3NS89w8Js3TZ5kvABZg6nIaqnJBtgbtjSDzmg3qh3NC6Mj6kR9KVUzmY1A9ONDQ/qyExAMhDAoEfQgCfs0wiIeQGWb+lvVgKj0YjzTpai1j587EIs+wIopcD5+T2Av0wwbi7rgTWvjTrhm45/Zu/Dg1/JiaJe5tNZ9B74iG6BDN0cr4052IrKHg967J/GT53MPhzWW+Co7hDXj+cfMN/4cimTBGW09fHKyfMpxJdToAm39C4SpuQIBvHIaYJcUBIjmkw5KSS/cUqbRHJBNwOnHCifGwboT9cLRwxzY3vo29qGouPhriVmnE2evvcV2gMTTaqNFs6U6EGvDoGNsVBMQSaXtfEqQd4pM3rmhFlfJCLu5TQbdEe8MR231krSSsVAshoEbjuc53nDyTamX0e+pbBmH6R9CmdSM12Ia3r4ZR0FY60A9iB0oY2n+ic9uRkyxVRpe1I0VgcnDUFbHu/nZIV6CzF1XWENF2vK3FdPq2JcL3fkbg3xxKDD91Kn0gQ4p0/VLBlJmEu5pYBbV+L3XkDfvZI7jXUyRkxflUmGMRhCVh5atelryERCX2U5StNuNps3OvA96iZlErpGtOeXJLhppXLG9UwRqYCh9ZCnn7GUo17qmUPPcqNTwWlpquD7PTMNGtKn9dHVP4bm42clL85dXfpfmQSG0CgdVppyJ46kWf7HUhAz5PsREOurQ39vVDmJ1hY56YNPM8Kl7tEwzO/G7AXSWsUIcqN0snIsYNz8bnUEXIfJNjIfaPSFxiPiKov9MHh784NShch7+zonguY61WRLP4OMEmd+m4Nf0rOwbg/7o6TrRrfjoxI0I8UdJxyFtRVz45tZYrn/9Z8Fc1ks3JO";
        System.out.println(decrypt(DES_KEY, data));
//        System.out.println(encrypt(DES_KEY, str));

    }


}